import { _decorator, Component, Graphics, UITransform, tween, Vec3, Vec2, Color, EventTouch, NodeEventType, Material } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('MouseLineEffect')
export class MouseLineEffect extends Component {
    @property(Graphics)
    graphics: Graphics | null = null;

    @property({ type: Number })
    fadeDuration: number = 1.0;

    private points: Vec2[] = [];
    private currentTween: any = null;

    onLoad() {
        // 初始化Graphics组件
        this.graphics = this.getComponent(Graphics) || this.addComponent(Graphics);
        this.graphics.lineWidth = 5;
        this.graphics.strokeColor = Color.RED;

        // 设置支持透明度的材质
        const mat = this.graphics.material || new Material();
        mat.initialize({
            effectName: 'builtin-unlit',
            defines: { USE_TEXTURE: false, USE_VERTEX_COLOR: true }
        });
        this.graphics.material = mat;
        mat.setProperty('opacity', 1);

        // 注册触摸事件
        this.node.on(NodeEventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(NodeEventType.TOUCH_END, this.onTouchEnd, this);
    }

    onTouchMove(event: EventTouch) {
        const location = event.getUILocation();
        const uiTransform = this.node.getComponent(UITransform)!;
        const localPos = uiTransform.convertToNodeSpaceAR(new Vec3(location.x, location.y, 0));
        
        this.points.push(new Vec2(localPos.x, localPos.y));
        this.drawLine();
        this.resetFadeTimer();
    }

    onTouchEnd() {
        this.startFadeAnimation();
    }

    drawLine() {
        this.graphics!.clear();
        if (this.points.length < 2) return;
        
        this.graphics!.moveTo(this.points[0].x, this.points[0].y);
        for (let i = 1; i < this.points.length; i++) {
            this.graphics!.lineTo(this.points[i].x, this.points[i].y);
        }
        this.graphics!.stroke();
    }

    resetFadeTimer() {
        if (this.currentTween) {
            this.currentTween.stop();
            this.graphics!.getMaterial(0)!.setProperty('opacity', 1);
        }
    }

 startFadeAnimation() {
        const material = this.graphics!.getMaterial(0)!;
        
        // ✅ 正确的tween用法
        this.currentTween = tween({ opacity: 1 })
            .to(this.fadeDuration, { opacity: 0 }, {
                // 使用onUpdate替代原来的错误写法
                onUpdate: (target: any, ratio: number) => {
                    const currentOpacity = 1 - ratio;
                    material.setProperty('opacity', currentOpacity);
                }
            })
            .call(() => {
                this.graphics!.clear();
                this.points = [];
            })
            .start();
    }

    onDestroy() {
        this.node.off(NodeEventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(NodeEventType.TOUCH_END, this.onTouchEnd, this);
    }
}